//
//  OMConsumerGoodsViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2016/12/14.
//  Copyright © 2016年 Kamfat. All rights reserved.
//

#import "OMConsumerGoodsViewController.h"
#import "OMShoppingCartViewController.h"
#import "OMOrderSubmitViewController.h"
#import "BaseTableView.h"
#import "BaseCollectionViewCell.h"

#import "OMMallCategoryItem.h"
#import "OMConsumerGood.h"
#import "OMConsumerListHeader.h"

#import "OMSearchBar.h"

#import "OMConsumerGoodOneColumnLayout.h"
#import "OMConsumerGoodsCollectDelegater.h"
#import "KTConsumerGoodCategoryCollectCell.h"

#import "OMCategory.h"

#define kSectionHeight SM_SIZE(90)
#define kRedColor SM_dotRedColor

#define kLineColor HEXCOLOR(@"e9e9e9")

#import "OMCategoryFilterView.h"
#import "OMFakeCategoryData.h"
#import "OMGoodResponse.h"


/** 综合排序*/
NSString *const SortTypeTopDesc = @"topDesc";
/** 价格升序*/
NSString *const SortTypePriceAsc = @"priceAsc";
/** 价格降序*/
NSString *const SortTypepriceDesc = @"priceDesc";
/** 销量降序*/
NSString *const SortTypeSalesDesc = @"salesDesc";
/** 评分降序*/
NSString *const SortTypeScoreDesc = @"scoreDesc";
/** 日期降序*/
NSString *const SortTypeDateDesc = @"dateDesc";


@interface OMConsumerGoodsViewController () <UICollectionViewDelegate,UICollectionViewDataSource,OMSearchBarDelegate>

@property (nonatomic, strong) OMCategoryFilterView *filterView;
@property (nonatomic, strong) UICollectionView *goodCollectView;
@property (nonatomic, strong) OMConsumerGoodsCollectDelegater *goodDelegater;
@property (nonatomic, strong) UICollectionView *collectView;
//第个单元添加数量
@property (nonatomic, strong) NSMutableDictionary *numberDictionary;
//分区添加数量
@property (nonatomic, strong) NSMutableDictionary *sectionNumDictionary;

@property (nonatomic, assign) NSUInteger selectedSection;

@property (nonatomic, strong) NSArray <OMCategory *>*categorys;
@property (nonatomic, strong) NSMutableArray <OMProduct *>*goods;
@property (nonatomic, strong) NSArray <OMCategory *>*secCateogrys;

@property (nonatomic, copy) NSString *selectedCategoryId;
@property (nonatomic, copy) NSString *sortType;
@property (nonatomic, assign) NSUInteger pageNumber;
@property (nonatomic, assign) NSUInteger pageSize;

@end



@implementation OMConsumerGoodsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.numberDictionary = [NSMutableDictionary dictionary];
    self.sectionNumDictionary = [NSMutableDictionary dictionary];

    [self configure];

    @weakify(self);
    [SMNotificationMonitorRACSignal(OM_NOTIFICATION_KEY_LOGIN_SUCCESS) subscribeNext:^(id x) {
        @strongify(self);
        [self reloadDataFromNetWork];
    }];

    [self startAnimating:YES];
    [self getCategorys];
}

- (UIColor *)navigationColor
{
    return SM_naviSubColor;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    SMNotificationPost(SM_NOTIFACATION_NEED_CARTITEM_SHOW, nil);
}

- (void)configure
{
    _goods = [NSMutableArray array];
    //分页
    @weakify(self);
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        self.pageNumber++;
        [self getServiceData];
    }];
    footer.stateLabel.font = SM_CFont(24);
    footer.stateLabel.textColor = SM_darkGrayColor;
    footer.triggerAutomaticallyRefreshPercent = SM_SIZE(-20);
    footer.automaticallyHidden = true;
    [footer setTitle:@"我也是有底线的" forState:MJRefreshStateNoMoreData];
    self.goodCollectView.mj_footer = footer;

    //分类视图
    self.view.backgroundColor = HEXCOLOR(@"#FfFfFf");
    self.automaticallyAdjustsScrollViewInsets = false;
    [self.collectView registerClass:[KTConsumerGoodCategoryCollectCell class] forCellWithReuseIdentifier:[KTConsumerGoodCategoryCollectCell cellIdentifier]];
    [self.view insertSubview:self.collectView atIndex:0];
    CGFloat filterViewHeight = SM_SIZE(90);
    [self.view insertSubview:self.goodCollectView atIndex:0];
    [self.collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.width.equalTo(@((SM_SCREEN_WIDTH*2.f)/8.f));
        make.bottom.equalTo(self.goodCollectView.mas_bottom);
        make.top.equalTo(self.navigationBar.mas_bottom);
    }];
    
    //过滤
    _filterView = [OMCategoryFilterView new];
    _filterView.backgroundColor = HEXCOLOR(@"#F6F6F6");
    [_filterView setLayoutHandler:^{
        @strongify(self);
        [self.goodDelegater changeLayout];
    }];
    [_filterView setSelectionHandler:^(NSUInteger sec, NSUInteger row) {
        @strongify(self);
        if (self.secCateogrys.count && sec == 0) {
            self.selectedCategoryId = self.secCateogrys[row].id;
        }else {
            self.sortType = @[SortTypeTopDesc,
                              SortTypePriceAsc,
                              SortTypepriceDesc,
                              SortTypeSalesDesc,
                              SortTypeScoreDesc,
                              SortTypeDateDesc]
            [row];
            [self getServiceData];
        }
    }];
    [self.view addSubview:_filterView];
    [_filterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom);
        make.left.equalTo(self.goodCollectView.mas_left);
        make.right.equalTo(self.goodCollectView.mas_right);
        make.height.equalTo(@(filterViewHeight));
    }];

    UIView *line = [UIView new];
    line.backgroundColor = SM_naviShadowColor;
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.collectView.mas_right);
        make.width.equalTo(@(.5f));
        make.top.equalTo(self.collectView.mas_top);
        make.bottom.equalTo(@(SM_SIZE(0)));
    }];

    [self.goodCollectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.collectView.mas_right).offset(SM_SIZE(0));
        make.right.equalTo(@0);
        make.bottom.equalTo(@0);
        make.top.equalTo(_filterView.mas_bottom);
    }];

    //搜索栏与返回键的共存
    OMSearchBar *searchBar = [OMSearchBar new];
    searchBar.delegate = self;
    searchBar.showCancelButton = NO;
    if (self.navigationController.viewControllers.count>1) {
        searchBar.frame = CGRectMake(SM_SIZE(100), 0, SM_SCREEN_WIDTH-SM_SIZE(120), SM_SIZE(60));
    }else {
        searchBar.frame = CGRectMake(SM_SIZE(0), 0, SM_SCREEN_WIDTH-SM_SIZE(20), SM_SIZE(60));
    }
    self.navigationItem.title = nil;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:searchBar];

}

- (void)reloadDataFromNetWork
{
    [self getCategorys];
}


/**
 获取一级分类
 */
- (void)getCategorys
{
    [KTHttpUtils
     GET:@"productCategory/findGrade.jhtml"
     parameters:nil
     needCache:false
     needToken:false
     progress:nil
     completion:^(id responseObject, BOOL isSuccess, NSString *message) {
         if (isSuccess) {
             _categorys = [OMCategory mj_objectArrayWithKeyValuesArray:responseObject[OMDatumKey]];
             if (_categorys.count) {
                 _selectedSection = 0;
                 for (OMCategory *category in self.categorys) {
                     if ([category.id isEqualToString:self.categoryBridgeId]) {
                         self.selectedSection = [self.categorys indexOfObject:category];
                         break;
                     }
                 }
                 self.selectedSection = self.selectedSection;
             }
             [self.collectView reloadData];
         }else {
             [self showNetWorkError];
         }
     }];
}


/**
 获取二级分类
 */
- (void)getSubCategorys
{
    [self startAnimating:true];
    [KTHttpUtils
     GET:@"productCategory/findChildren.jhtml"
     parameters:@{@"id":self.categorys[self.selectedSection].id}//分类id
     needCache:false
     needToken:false
     progress:nil
     completion:^(id responseObject, BOOL isSuccess, NSString *message) {
         if (isSuccess) {
             self.secCateogrys = [OMCategory mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]];
         }else {
             self.secCateogrys = nil;
         }
     }];
}


/**
 获取商品列表
 */
- (void)getServiceData
{
    NSLog(@"pageNumber=%ld,pageSize=%ld",self.pageNumber,self.pageSize);
    self.goodCollectView.mj_footer.isRefreshing?:[self startAnimating:true];
    [KTHttpUtils GET:@"productCategory/findGoods.jhtml"
          parameters:@{
                       @"id":self.selectedCategoryId,   //分类id
                       @"orderType":self.sortType,      //排序
                       @"pageNumber":@(self.pageNumber),//分页:第x页
                       @"pageSize":@(self.pageSize),    //分页:共x页
                       }
            progress:nil
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {

              if (isSuccess) {
                  //Data parse
                  OMGoodResponse *response = [OMGoodResponse mj_objectWithKeyValues:responseObject[OMDatumKey]];
                  [response fullFillImageStrWithPrefix:responseObject[OMImagePrefix]];

                  //UI reload
                  if (!self.goodCollectView.mj_footer.isRefreshing) {
                      [self.goods removeAllObjects];
                  }
                  [self.goods addObjectsFromArray:response.list];
                  self.pageNumber == response.totalPage?[self.goodCollectView.mj_footer endRefreshingWithNoMoreData]:[self.goodCollectView.mj_footer endRefreshing];
                  [self reload];
                  //停止页面的加载动画
                  [self startAnimating:NO];
                  [self.goodCollectView reloadData];

              } else {
                  if (self.goodCollectView.mj_footer.isRefreshing) {
                      [self.goodCollectView.mj_footer endRefreshing];
                      self.pageNumber --;
                  }
                  [OMHUD HUDInfo:message];
                  [self showNetWorkError];
              }
          }];
}

#pragma mark - collect view delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _categorys.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KTConsumerGoodCategoryCollectCell *cell = [KTConsumerGoodCategoryCollectCell collectCellWithCollectionView:collectionView atIndexPath:indexPath];
    cell.titleLabel.text = _categorys[indexPath.item].name;
    cell.kt_selected = self.selectedSection == indexPath.item;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedSection = indexPath.item;
    [self.collectView reloadData];
}

#pragma mark - Setters
BOOL isAnimating = NO;
- (void)setSelectedSection:(NSUInteger)selectedSection
{
    _selectedSection = selectedSection;
    self.pageNumber = 0;
    [self getSubCategorys];
}

- (void)setSecCateogrys:(NSArray<OMCategory *> *)secCateogrys_
{
    _secCateogrys = secCateogrys_;
    self.selectedCategoryId = self.categorys[self.selectedSection].id;
    if (self.secCateogrys.count) {

        NSMutableArray *secCategoryTitles = [NSMutableArray array];
        OMCategory *category = [OMCategory new];
        category.name = @"全部分类";
        category.id = self.categorys[self.selectedSection].id;
        NSMutableArray *secCategorys = [NSMutableArray arrayWithArray:_secCateogrys];
        [secCategorys insertObject:category atIndex:0];
        _secCateogrys = secCategorys;
        for (OMCategory *category in self.secCateogrys) {
            [secCategoryTitles addObject:category.name];
        }
        [self.filterView setItems: @[
                                     @{@"title":@"全部分类",
                                       @"items":secCategoryTitles},
                                     @{@"title":@"综合排序",
                                       @"items":@[@"综合排序",@"价格最低",@"价格最高",@"销量最高",@"评分最高",@"最新发布"]},
                                     ]];
    }else {
        [self.filterView setItems: @[
                                     @{@"title":@"综合排序",
                                       @"items":@[@"综合排序",@"价格最低",@"价格最高",@"销量最高",@"评分最高",@"最新发布"]},
                                     ]];
    }
}

- (void)setSelectedCategoryId:(NSString *)selectedCategoryId
{
    _selectedCategoryId = selectedCategoryId;
    self.goodCollectView.contentOffset = CGPointZero;
    self.pageNumber = 1;
    [self getServiceData];
}


- (void)reload
{
    self.goodDelegater.goods = self.goods;
}


#pragma mark - Actions
- (void)submitAction:(UIButton *)sender
{
    NSMutableArray *goods = [NSMutableArray array];
    for (OMConsumerGoodContainer *category in self.categorys) {
        for (OMConsumerGood *good in category.detail) {
            if (good.quantity) {
                [goods addObject:good];
            }
        }
    }
    if (!goods.count) {
        [OMHUD HUDInfo:@"请选择商品"];
        return;
    }
    [KTHttpUtils GET_NOCACHE:@"app/memberResource" parameters:nil progress:nil completion:^(id responseObject, BOOL isSuccess, NSString *message) {
        if (isSuccess) {
            OMDeliveryInfo *info = [OMDeliveryInfo mj_objectWithKeyValues:responseObject[OMDataKey][@"receiver"]];
            NSArray *coupons = [OMCheapModel mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey][@"coupon"]];
            NSMutableDictionary *parameter = [@{@"consumerGoods":goods,@"coupons":coupons?coupons:@[]} mutableCopy] ;
            if (info) {
                [parameter setObject:info forKey:@"deliveryInfo"];
            }
            NaviPush(@"OMOrderSubmitViewController", parameter);
        }else {
            [OMHUD HUDInfo:message];
        }
    }];
}


- (BOOL)hasNum
{
    BOOL hasNum = NO;
    for (OMConsumerGoodContainer *category in self.categorys) {
        for (OMConsumerGood *good in category.detail) {
            if (good.quantity) {
                hasNum = YES;
                return hasNum;
            }
        }
    }
    return hasNum;
}


#pragma mark - OMSearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(OMSearchBar *)searchBar
{
    NaviPush(@"OMGoodSearchViewController", nil);
    return NO;
}


#pragma mark - Getters
- (UICollectionView *)collectView
{
    if (!_collectView) {
        _collectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SM_SCREEN_WIDTH/4, SM_SCREEN_HEIGHT-64) collectionViewLayout:[self layout]];
        //设置代理
        _collectView.dataSource = self;
        _collectView.delegate = self;
        _collectView.scrollEnabled = YES;
        _collectView.alwaysBounceVertical = YES;
        _collectView.backgroundColor = HEXCOLOR(@"#F6F6F6");
        _collectView.showsVerticalScrollIndicator = false;
    }
    return _collectView;
}

- (UICollectionView *)goodCollectView
{
    if (_goodCollectView == nil) {
        _goodCollectView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:[OMConsumerGoodOneColumnLayout new]];
        _goodDelegater = [[OMConsumerGoodsCollectDelegater alloc]initWithCollectionView:_goodCollectView];
        _goodCollectView.contentInset = UIEdgeInsetsMake(SM_SIZE(0), 0, 0, 0);
        _goodCollectView.backgroundColor = SM_whiteColor;

    }
    return _goodCollectView;
}

- (UICollectionViewLayout*)layout
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    float itemSize = (SM_SCREEN_WIDTH*2.f)/8.f;
    flowLayout.itemSize = CGSizeMake(itemSize, itemSize/2.f);
    return flowLayout;
}

- (NSString *)sortType
{
    if (!_sortType) {
        _sortType = SortTypeTopDesc;
    }
    return _sortType;
}

- (NSUInteger)pageSize
{
    if (!_pageSize) {
        _pageSize = 20;
    }
    return _pageSize;
}

- (NSUInteger)pageNumber
{
    if (!_pageNumber) {
        _pageNumber = 1;
    }
    return _pageNumber;
}
@end
